# coding=utf-8
# 全世界最帅的帅哥
# Definition for singly-linked list.
# https://leetcode.cn/problems/merge-two-sorted-lists/description/
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        if not list1 or not list2:
            return list1 if list2 else list2

        head = list1 if list1.val < list2.val else list2
        node = head
        node1 = head.next
        node2 = list2 if head == list1 else list2

        while node1 and node2:
            if node1.val < node2.val:
                head.next = node1
                node1 = node1.next
            else:
                head.next = node2
                node2 = node2.next
            head = head.next
        head.next = node1 if node1 else node2
        return node


